<template>
	<div class="management-box">
		<!-- todo 数据管理 -->
		<div class="management-left">
			<div class="management-title">
				<img src="@img/main/path.png" />
				<span>数据目录</span>
			</div>
			<div class="management-list">
				<el-tree
					ref="treeRef"
					:data="ftpList"
					:props="defaultProps"
					node-key="name"
					@node-click="loadFileList"
					default-expand-all
					:key="treeKey"
				>
					<template #default="{ node }">
						<div class="custom-tree-node">
							<div><img :src="fileIMG" alt="" />{{ node.label }}</div>
						</div>
					</template>
				</el-tree>
			</div>
		</div>
		<div class="management-right">
			<div class="search-list">
				<!-- <el-button class="elBtn update-btn" @click="dealUpdate">
					<img src="@img/main/refresh.png" />
					更新数据
				</el-button> -->
				<div style="width: 200px">{{ currentPath }}</div>

				<div class="keyword-input">
					<el-input
						v-model="keyword"
						class="m-2 w-48"
						placeholder="搜索关键字"
						clearable
						@clear="dealUpdate"
					>
					</el-input>
				</div>
				<el-button class="elBtn search-btn" @click="dealSearch">
					<img src="@img/main/search-light.png" />
					查询
				</el-button>
				<el-button class="elBtn reset-btn" @click="resetSearch"> 重置 </el-button>
				<el-button class="elBtn reset-btn" @click="downloadftps"> 批量下载 </el-button>
				<div class="file-tool">数据上传工具:</div>
				<div class="start-tool" @click="startFTP">启动</div>
				<div class="upload-tool" @click="downloadFTP">下载</div>
			</div>
			<div class="table-area">
				<el-table
					v-loading="listLoading"
					class="list-table"
					ref="datatable"
					:data="tableData"
					:header-cell-style="{
						background: '#113659',
						fontWeight: 400,
						color: '#fff',
					}"
					:header-row-style="{ background: '#113659' }"
					:row-style="{ background: '#0a2641' }"
					:cell-style="{ background: '#0a2641', borderBottom: '1px solid #184168', color: '#fff' }"
					:max-height="tableHeight"
				>
					<el-table-column type="selection" :selectable="selectable" width="55" />
					<el-table-column fixed prop="fileName" label="名称" width="320" show-overflow-tooltip>
					</el-table-column>
					<el-table-column prop="unknown1" label="数据类型" width="120">
						<template #default="{ row }">
							<span>{{ row.type === "1" ? "栅格数据" : "矢量数据" }}</span>
							<!-- <span>{{ row.type }}</span> -->
						</template>
					</el-table-column>
					<el-table-column prop="unknown2" label="数据格式" width="128">
						<template #default="{ row }">
							<span>{{ row.type === "1" ? "tif" : "shp" }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="fileSize"
						label="数据大小(MB)"
						width="218"
						sortable
						:sort-method="sortMethod"
					>
					</el-table-column>
					<el-table-column prop="createTime" label="创建日期" width="218" sortable>
						<template #default="{ row }">
							<span>{{ new Date(row.createTime).toLocaleString() }}</span>
						</template>
					</el-table-column>
					<!-- <el-table-column prop="updateTime" label="修改日期">
						<template #default="{ row }">
							<span>{{ new Date(row.updateTime).toLocaleString() }}</span>
						</template>
					</el-table-column> -->
					<!-- <el-table-column prop="unknown2" label="创建人" width="168"> </el-table-column> -->
					<el-table-column prop="uploadStatus" label="状态" width="168">
						<template #default="{ row }">
							<!-- 两种情况：已入库，未入库 -->
							<div v-if="row.uploadStatus == 1" class="data-tag">已入库</div>
							<div v-else class="data-tag data-tag-off">未入库</div>
						</template>
					</el-table-column>
					<!-- 操作 -->
					<el-table-column label="操作" min-width="218">
						<template #default="{ row }">
							<!--							<el-button type="primary" link @click="dealEdit(row)">详情</el-button>-->
							<!--							<el-button type="primary" link @click="dealEdit(row)">预览</el-button>-->
							<el-button type="primary" v-if="row.type == '1'" link @click="yuanData(row)"
								>元数据</el-button
							>
							<el-button type="primary" link @click="downloadRow(row)">下载</el-button>
							<el-button type="primary" link @click="deleteRow(row)">删除</el-button>
							<!-- <el-button type="primary" link @click="dealReset(row)">重置</el-button>
							<el-button type="primary" link @click="dealDelete(row)">删除</el-button> -->
						</template>
					</el-table-column>
				</el-table>
				<el-dialog v-model="resultDialog" title="元数据" width="850px" append-to-body>
					<div class="metadata">
						{{ metaData }}
					</div>
				</el-dialog>
			</div>
		</div>
	</div>
	<el-dialog v-model="dialogVisible" title="下载进度">
		<!-- <el-progress :percentage="progress"></el-progress>
            <span>下载进度: {{ progress }}%</span> -->
		<div v-for="item in arrDownload" :key="item.id">
			<div class="download-item">
				<div class="download-item-name">{{ item.fileName }}</div>
				<el-progress :percentage="item.progress" />
			</div>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button type="primary" @click="confirmDownload">确定</el-button>
				<el-button @click="handleClose">取消</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import fileIMG from "@img/main/file.png";
import { ElMessage, ElMessageBox, ElTree, ElTable } from "element-plus";
import {
	deleteData,
	downloadData,
	getUserFileList,
	queryData,
	getqueryDirs,
	refreshData,
	getqueryletaData,
} from "@/api/data-management/index";
import { download } from "@/utils/request";

import { handleTreeData } from "@/utils/tsTools";
import { dataListItem } from "@/api/ai-processing/types";
import { useUserStore } from "@/store";
import { log } from "console";
const treeKey = ref(0);
const resultDialog = ref(false);
const dialogVisible = ref(false);
const userStore = useUserStore();
const getUserCode = computed(() => userStore.userCode);
const metaData = ref();
// #region 侧边栏业务
interface Tree {
	name: string;
	children?: Tree[];
	file?: Array<string>;
	id?: number;
}
const ftpList: Ref<Tree[]> = ref([]);
const defaultProps = {
	children: "children",
	label: "name",
};
const datatable = ref<InstanceType<typeof ElTable>>();
// 默认选择根目录
const treeRef = ref<InstanceType<typeof ElTree>>();
const tableHeight = ref(0);
onMounted(async () => {
	if (typeof getUserCode.value === "undefined") {
		return;
	}
	// let { data: fileList } = await getUserFileList(getUserCode.value, false);
	let { data: fileList } = await getqueryDirs("");

	ftpList.value = fileList.children;
	/* 默认获取dom 勾选第一项 */
	await nextTick();
	treeRef.value?.$el.querySelector(".el-tree-node__content")?.click();
	//计算table最大高度
	tableHeight.value = window.innerHeight - 250;
	console.log("文件列表：", fileList);
});
// 加载文件夹中的数据列表
const updateChildrenRecursively = (list: any, targetId: any, childrenData: any) => {
	for (let item of list) {
		if (item.id === targetId) {
			item.children = childrenData;
			return list;
		}
		if (item.children && item.children.length > 0) {
			// 递归处理子节点
			// console.log(item.children, targetId, childrenData, "递归处理子节点");
			updateChildrenRecursively(item.children, targetId, childrenData);
		}
	}
};
const findPathById = (list: any, targetId: any, path = []) => {
	for (let item of list) {
		if (item.id === targetId) {
			return [...path, item.name]; // 找到目标节点，返回拼接的路径
		}
		if (item.children && item.children.length > 0) {
			// 递归查找子节点
			const result = findPathById(item.children, targetId, [...path, item.name]);
			if (result.length > 0) {
				return result; // 如果找到路径，返回
			}
		}
	}
	return []; // 如果没有找到，返回空数组
};
const currentPath = ref("");
const loadFileList = async (data: any, node?: any) => {
	const path = findPathById(ftpList.value, data.id);
	let name = path.join("\\");
	currentPath.value = name;

	let res = await getqueryDirs(name);
	if (res.data.children.length > 0) {
		updateChildrenRecursively(ftpList.value, data.id, res.data.children);
	}
	tableData.value = res.data.files;
	nextTick(() => {
		const tree = treeRef.value;
	});
	// currentFile = data;
};
// #endregion
let currentFile: any;
const listLoading = ref(false);
const tableData: Ref<dataListItem[]> = ref([]);
// 排序 数据可能是字符串'13MB' '234MB'
const sortMethod = (a: any, b: any) => {
	let aNum = a.fileSize.replace("Mb", "");
	let bNum = b.fileSize.replace("Mb", "");
	return Number(aNum) - Number(bNum);
};
const dealEdit = (row: dataListItem) => {
	// console.log(row);
	alert("暂不支持，敬请期待");
};
const dealSearch = async () => {
	if (keyword.value) {
		let res = await queryData(keyword.value);
		if (res && res.code === 200) {
			tableData.value = res.data;
		} else {
			ElMessage.error("查询失败");
		}
	}
};
const resetSearch = () => {
	keyword.value = "";
	dealSearch();

	// dealUpdate();
};
const dealUpdate = async () => {
	listLoading.value = true;
	await new Promise<void>((resolve, reject) => {
		setTimeout(() => {
			if (!getUserCode.value) {
				return;
			}
			refreshData(getUserCode.value).then(() => {
				resolve();
			});
		}, 0);
	});

	if (typeof getUserCode.value === "undefined") {
		return;
	}
	// let { data: fileList } = await getUserFileList(getUserCode.value, false);
	let { data: fileList } = await getqueryDirs("test");

	ftpList.value = fileList.children;
	listLoading.value = false;
	loadFileList(ftpList.value[0]);
};
const downloadFTP = () => {
	window.open(BASE_CONFIG.FTPURL);
};
const selectable = (row: any) => ![1, 31].includes(row.id);
const ftpIP = computed(() => userStore.ftpInfo);
const userName = computed(() => userStore.userName);
const ftpPwd = computed(() => userStore.ftpPwd);

const startFTP = () => {
	let ip = ftpIP.value.split("//")[1].split(":")[0];
	let port = ftpIP.value.split("//")[1].split(":")[1];
	openUrlWithInputTimeoutHack(
		BASE_CONFIG.FTPStartURL +
			"message/?IP=" +
			ip +
			"&Port=" +
			port +
			"&user=" +
			userName.value +
			"&password=" +
			ftpPwd.value +
			"&userCode=" +
			getUserCode.value +
			"&serviceIp=" +
			BASE_CONFIG.serviceIp +
			"&servicePort=" +
			BASE_CONFIG.servicePort,
		() => {
			console.log("未安装");
			ElMessageBox.confirm("未监测到数据上传工具，是否下载？", {
				confirmButtonText: "下载",
				cancelButtonText: "取消",
			}).then(() => {
				downloadFTP();
			});
		},
		() => {
			console.log("已安装，自动唤起");
			// startFTP1();
		}
	);
};
const startFTP1 = () => {
	// fft://message/?IP=192.168.0.16&Port=20000&user=123&password=123
	let ip = ftpIP.value.split("//")[1].split(":")[0];
	let port = ftpIP.value.split("//")[1].split(":")[1];
	console.log(
		BASE_CONFIG.FTPStartURL +
			"message/?IP=" +
			ip +
			"&Port=" +
			port +
			"&user=" +
			userName.value +
			"&password=" +
			ftpPwd.value +
			"&userCode=" +
			getUserCode.value
	);
	window.open(
		BASE_CONFIG.FTPStartURL +
			"message/?IP=" +
			ip +
			"&Port=" +
			port +
			"&user=" +
			userName.value +
			"&password=" +
			ftpPwd.value +
			"&userCode=" +
			getUserCode.value,
		"_self"
	);
};
const yuanData = async (row: any) => {
	console.log(row, "yuanData");
	resultDialog.value = true;
	let res = await getqueryletaData(row.filePath);
	metaData.value = res.data;
};
const downloadRow = (row: any) => {
	console.log(row, "dowanloadRow");

	if (row.type === "1") {
		// downloadData(row.filePath);
		downloadFTPfilePath(row.filePath);
	} else {
		// downloadData(row.zipFilePath);
		downloadFTPfilePath(row.zipFilePath);
	}
};
const arrDownload = ref([] as any);

const downloadftps = () => {
	let arr = (datatable.value as any).getSelectionRows();
	let baseURL = BASE_CONFIG["baseURL"];
	arr.forEach((item: any) => {
		let iframe = document.createElement("iframe"); // 创建 iframe 标签
		iframe.style.display = "none"; // 隐藏 iframe
		console.log(encodeURI(baseURL + "/common/download/ftp?" + "filePath=" + item.filePath));

		iframe.src = encodeURI(baseURL + "/common/download/ftp?" + "filePath=" + item.filePath); // 设置 iframe 的 src 为文件地址
		document.body.appendChild(iframe); // 将 iframe 添加到文档中
	});
	// arrDownload.value = arr.map((item) => {
	// 	item.process = 0; // 初始化进度
	// 	return { ...item }; // 返回新的对象，保持原对象不变
	// });
	// dialogVisible.value = true;
	// console.log(arrDownload.value, "arrDownload.value");
};
const confirmDownload = () => {
	let arr = (datatable.value as any).getSelectionRows();
	downloadAjax(arr);
};
const handleClose = () => {
	dialogVisible.value = false;
};
watch(
	arrDownload,
	(newVal) => {
		newVal.forEach((item) => {
			watch(
				() => item.progress,
				(newProcess) => {
					console.log(`文件 ${item.filePath} 进度更新: ${newProcess}%`);

					// 检查是否所有文件的进度都为 100
					if (newVal.every((file) => file.progress === 100)) {
						dialogVisible.value = false; // 关闭弹窗
					}
				}
			);
		});
	},
	{ deep: true }
);
const downloadAjax = async (items: any[]) => {
	console.log(arrDownload.value, "arrDownload.value");

	for (const item of arrDownload.value) {
		let filePath = item.filePath;
		try {
			await download({
				url: "/common/download/ftp",
				params: {
					filePath,
				},
				onDownloadProgress: (progressEvent: any) => {
					item.progress = Math.round(progressEvent.progress * 100);
				},
			});
			ElMessage.success("下载成功"); // 成功消息在每次下载后显示
		} catch (error) {
			console.error("下载失败", error); // 可以选择是否继续或停止
			break; // 如果希望在失败时停止下载，使用 break
		}
	}
};
const downloadFTPfilePath = (filePath: string) => {
	let baseURL = BASE_CONFIG["baseURL"];
	window.location.href = baseURL + "/common/download/ftp?" + "filePath=" + encodeFilePath(filePath);
};
const encodeFilePath = (filePath: any) => {
	const normalizedPath = filePath.replace(/\\/g, "\\\\");
	return encodeURIComponent(normalizedPath);
};
const deleteRow = (row: { id: string; fileName: string }) => {
	ElMessageBox.confirm("确认删除名称为：" + row.fileName + " 的数据?", {
		confirmButtonText: "确认",
		cancelButtonText: "取消",
	}).then(() => {
		deleteData(row.id)
			.then(() => {
				ElMessage.success("删除成功");
				dealUpdate();
			})
			.catch(() => {
				ElMessage.error("删除失败");
			});
	});
};
/* 搜索 */
const keyword = ref("");

function openUrlWithInputTimeoutHack(url, failCb, successCb) {
	let target = document.createElement("input");
	target.style.width = "0";
	target.style.height = "0";
	target.style.position = "fixed";
	target.style.top = "0";
	target.style.left = "0";
	document.body.appendChild(target);

	target.focus();
	var handler = _registerEvent(target, "blur", onBlur);
	console.log("focus");
	function onBlur() {
		console.log("blur");
		successCb && successCb();
		handler.remove();
		clearTimeout(timeout);
		document.body.removeChild(target);
	}

	//will trigger onblur
	location.href = url;

	// Note: timeout could vary as per the browser version, have a higher value
	var timeout = setTimeout(function () {
		console.log("setTimeout");
		failCb && failCb();
		handler.remove();
		document.body.removeChild(target);
	}, 1000);
}

function _registerEvent(target, eventType, cb) {
	if (target.addEventListener) {
		target.addEventListener(eventType, cb);
		return {
			remove: function () {
				target.removeEventListener(eventType, cb);
			},
		};
	} else {
		target.attachEvent(eventType, cb);
		return {
			remove: function () {
				target.detachEvent(eventType, cb);
			},
		};
	}
}
</script>

<style lang="scss" scoped>
@import "@/index.scss";
.metadata {
	height: 500px;
	width: 100%;
	overflow: auto;
}
.management-box {
	@apply absolute right-0 z-20 m-auto flex h-full text-white;
	top: 4rem;
	left: 70px;
	width: calc(100% - 12px - 60px);
	height: calc(100% - 4rem - 10px);
	display: flex;
}
.management-left {
	@apply mr-3 flex flex-col;
	// top: 100px;
	min-width: 238px;
	padding: 0 9px;
	background: #0a2641;
	border-radius: 4px;
	border: 1px solid #376699;
	.management-title {
		@apply flex items-center;
		height: 44px;
		img {
			width: 16px;
			height: 16px;
			margin-left: 3px;
			margin-right: 8px;
		}
		span {
			@include art-font(18px, #ffffff);
		}
	}
	.management-list {
		@apply h-full;
		box-sizing: border-box;
		overflow: auto;
		padding: 0 6px;
		padding-top: 4px;
		background: linear-gradient(180deg, #1c4978 0%, #062a4e 100%);
		border-top: 1px solid #5ca1d7;
		--el-fill-color-light: rgba(7, 151, 255, 0.2);
		:deep(.el-tree) {
			background: transparent;
			color: #fff;
			.el-icon,
			.el-tree-node__expand-icon {
				display: none;
			}
			.el-tree-node__content {
				height: 32px;
				margin: 2px 0;
			}
			.el-tree-node__content:hover {
				.mouse-on {
					display: flex;
				}
			}
		}
		.custom-tree-node {
			@apply relative flex w-full pl-3;
			> div {
				@apply flex items-center;
				> img {
					@apply mr-2;
				}
			}
			> span {
				@apply absolute bottom-0 top-0 m-auto hidden items-center;
				right: 14px;
				> img {
					@apply mr-2;
				}
			}
		}
	}
}
.management-right {
	flex: 1;
	overflow: auto;
	background: #0a2641;
	border-radius: 4px;
	border: 1px solid #376699;
	padding: 20px 20px 36px 20px;
}
.search-list {
	@apply relative flex items-center;
	margin-bottom: 24px;
	.update-btn {
		width: 123px;
		height: 36px;
		margin-right: 18px;
		img {
			margin-right: 6px;
		}
	}
	.search-btn {
		width: 88px;
		height: 36px;
		margin-right: 8px;
		img {
			margin-right: 6px;
		}
	}
	.reset-btn {
		width: 72px;
		height: 36px;
		margin-right: 18px;
	}
	.keyword-input {
		width: 320px;
		margin-right: 18px;
		:deep(.el-input) {
			--el-input-bg-color: #0b1829;
			--el-input-icon-color: #656f7c;
			--el-input-border-color: #354867;
			--el-input-hover-border-color: rgba(64, 158, 255, 0.6);
			--el-input-text-color: rgba(203, 209, 219, 0.8);
			--el-input-border-radius: 4px;
			--el-input-focus-border-color: rgba(64, 158, 255, 0.6);
		}
	}
	.upload-tool {
		cursor: pointer;
		@apply absolute flex cursor-pointer select-none items-center justify-center;
		right: 28px;
		width: 58px;
		height: 40px;
		background: rgba(255, 255, 255, 0.06);
		border-radius: 4px;
		border: 1px solid #76c6ff;
		font-size: 14px;
		color: #76c6ff;
		img {
			margin-right: 8px;
		}
	}
	.file-tool {
		cursor: pointer;
		@apply absolute flex cursor-pointer select-none items-center justify-center;
		right: 166px;
		width: 158px;
		height: 40px;

		font-size: 14px;
		color: #76c6ff;
	}
	.start-tool {
		cursor: pointer;
		@apply absolute flex cursor-pointer select-none items-center justify-center;
		right: 106px;
		width: 58px;
		height: 40px;
		background: rgba(255, 255, 255, 0.06);
		border-radius: 4px;
		border: 1px solid #76c6ff;
		font-size: 14px;
		color: #76c6ff;
		img {
			margin-right: 8px;
		}
	}
}
.list-table {
	--el-table-border-color: none;
	background-color: transparent;
	@apply w-full;
	.data-tag {
		@apply flex items-center justify-center;
		width: 54px;
		height: 20px;
		background: #276eb7;
		border-radius: 50px 50px 50px 50px;
		&.data-tag-off {
			background: #d77820;
		}
	}
	.el-button {
		margin-right: 12px;
	}
	.el-table__empty-block {
		background-color: #0a2641;
	}
}
</style>
